//
//  ViewPlantSetTableViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 06/04/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewPlantSetTableViewController.h"
#import "PlantSet+CRUD.h"
#import "Plot+CRUD.h"
#import "AddToPlotViewController.h"
#import "UILabel+TextFont.h"

@interface ViewPlantSetTableViewController()
@property (nonatomic, strong) NSArray *plantArray;
@property (nonatomic, strong) NSManagedObjectContext *context;
@end


@implementation ViewPlantSetTableViewController
@synthesize plantSet = _plantSet;
@synthesize plantCell = _plantCell;
@synthesize plantArray = _plantArray;
@synthesize context = _context;

/*Retrieve a PlantSet object from CoreData based on the plant name that is passed into the class*/
- (void)selectPlantSet {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PlantSet"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@", self.plantSet.name];
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sorter];
    NSError *error;
    NSArray *results = [self.context executeFetchRequest:request error:&error];
    self.plantSet = [results objectAtIndex:0];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.context = self.plantSet.managedObjectContext;
    
    //Set the background image
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"paper.png"]];
    [tempImageView setFrame:self.tableView.frame]; 
    self.tableView.backgroundView = tempImageView;
    
    [self selectPlantSet];
    //Need to convert the array of plants into an NSMutableArray
    self.plantArray = [NSArray arrayWithArray:[self.plantSet.plants allObjects]];
    [self.tableView reloadData];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self setPlantCell:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.title = self.plantSet.name;
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.tableView reloadData];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 1){
        
        return [self.plantArray count];
    }
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1){
        return 57;
    }
    return 44;
}



-(UITableViewCell *)buildStaticCellsForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"addToPlotCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    if(indexPath.section == 0){
        cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
        cell.backgroundColor = [UIColor clearColor];
    }
    
    UILabel *addToPlotLabel = (UILabel *)[cell viewWithTag:5];
    [addToPlotLabel setMVBoliFont];
    UILabel *viewCompanionsLabel = (UILabel *)[cell viewWithTag:6];
    [viewCompanionsLabel setMVBoliFont];
    return cell;

}

-(UITableViewCell *)buildPlantCellsForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"plantCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"PlantListCell" owner:self options:nil];
        cell = _plantCell;
        self.plantCell = nil;
    }
    

    Plant *plant = [self.plantArray objectAtIndex:indexPath.row];
    
    UIImageView *thumbnail = (UIImageView *)[cell viewWithTag:1];
    thumbnail.image = [UIImage imageNamed:[plant.name stringByAppendingString:@"_S"]];
    
    UILabel *label = (UILabel *)[cell viewWithTag:2];
    label.text = plant.name;
    [label setSketchBlockFont];
    
    UIImageView *favourite = (UIImageView *)[cell viewWithTag:4];
    if([plant.isFavourite isEqualToNumber:[NSNumber numberWithBool:YES]]){
        favourite.image = [UIImage imageNamed:@"list_favourite_indicator"];
    }else{
        favourite.image = nil;
    }
    
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

-(UITableViewCell *)buildDeleteButtonCellForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"deleteButtonCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    
    UIButton *deleteButton = (UIButton *)[cell viewWithTag:1];
    [deleteButton setBackgroundImage:[[UIImage imageNamed:@"delete_button.png"]
                                      stretchableImageWithLeftCapWidth:8.0f
                                      topCapHeight:0.0f]
                            forState:UIControlStateNormal];
    
    [deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    deleteButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    deleteButton.titleLabel.shadowColor = [UIColor lightGrayColor];
    deleteButton.titleLabel.shadowOffset = CGSizeMake(0, -1);
    [deleteButton setHidden:YES];
    
    return cell;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        return [self buildStaticCellsForTableView:tableView atIndexPath:indexPath];
    }else if(indexPath.section == 1){
        return [self buildPlantCellsForTableView:tableView atIndexPath:indexPath];
    }else {
        return [self buildDeleteButtonCellForTableView:tableView atIndexPath:indexPath];
    }
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1){
        return YES;
    }else if(indexPath.section == 2){
        UITableViewCell *deleteCell = [self.tableView cellForRowAtIndexPath:indexPath];
        UIButton *deleteButton = (UIButton *)[deleteCell viewWithTag:1];
        if(self.tableView.editing == YES){
            [deleteButton setHidden:NO];
        }else{
            [deleteButton setHidden:YES];
        }
        return NO;
    }
    return NO;
}


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*Delete a PlantSet*/
- (IBAction)deletePressed:(id)sender 
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:nil,nil];
    
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet dismissWithClickedButtonIndex:1 animated:YES];
    [actionSheet showFromTabBar:self.tabBarController.tabBar];
}

/*Add a plant set to an existing plot*/
- (IBAction)addToPlotPressed:(id)sender 
{
    if([Plot checkIfPlotsExistInContext:self.context] == NO){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Plots!" message:@"Please create a plot first" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        [self performSegueWithIdentifier:@"addToPlotSegue" sender:self];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    
    if([segue.identifier isEqualToString:@"addToPlotSegue"]){
        
        UINavigationController *navCon = (UINavigationController *)segue.destinationViewController;
        AddToPlotViewController *addToPlotVC = [navCon.viewControllers objectAtIndex:0];
        [addToPlotVC setPlantsToAdd:[NSArray arrayWithArray:self.plantArray]];
    }
}

#pragma mark - UIActionSheet Delegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    switch (buttonIndex) {
        case 0:
            [PlantSet deletePlantSet:self.plantSet inContext:self.context];
            [self.navigationController popViewControllerAnimated:YES];
            break;
        default:
            break;
    }
}
@end
